package com.zzm.shortlink.admin.common.biz.user;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.zzm.shortlink.admin.common.convention.exception.ClientException;
import com.zzm.shortlink.admin.common.convention.result.Results;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

import static com.zzm.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
/**
 * 用户信息传输过滤器
 * UserTransmitFilter是一个过滤器，它在每个请求中从Redis获取用户信息，并将其设置到上下文中，然后在请求处理完成后清理上下文。这允许在请求处理期间访问用户信息。
 * 在整个过程中，UserTransmitFilter的doFilter方法在请求到达目标资源之前执行，并且它在响应返回给客户端之前清理资源。
 * 这使得过滤器非常适合用于请求的预处理和后处理，例如身份验证、日志记录、数据转换等
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String username = httpServletRequest.getHeader("username");
        if (StrUtil.isNotBlank(username)) {
            String userId = httpServletRequest.getHeader("userId");
            String realName = httpServletRequest.getHeader("realName");
            UserInfoDTO userInfoDTO = new UserInfoDTO(userId, username, realName);
            UserContext.setUser(userInfoDTO);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
//    private final StringRedisTemplate stringRedisTemplate;
//
//    private static final List<String> IGNORE_URI = Lists.newArrayList(
//            "/api/short-link/admin/v1/user/login",
////            "/api/short-link/admin/v1/user",
//            "/api/short-link/admin/v1/user/has-username",
////            "/api/short-link/admin/v1/create",
////            "/api/short-link/admin/v1/page",
//            "/api/short-link/admin/v1/user/check-login"
//    );
//
//    @SneakyThrows
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//        String requestURI = httpServletRequest.getRequestURI();
//        System.out.println("requestURI" + requestURI);
//        //如果不属于IGNORE_URI，那么就要验证token
//        if(!IGNORE_URI.contains(requestURI)){
//            //由于修改用户信息和用户注册都是同一个请求接口,而用户注册是不需要验证token的,所以这里区分一下这两个接口
//            String method = httpServletRequest.getMethod();
//            if(!(Objects.equals(requestURI, "/api/short-link/admin/v1/user") && Objects.equals(method, "POST"))){
//                String username = httpServletRequest.getHeader("username");
//                String token = httpServletRequest.getHeader("token");
//                if(!StrUtil.isAllNotBlank(username, token)){
//                    returnJson((HttpServletResponse) servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
//                    return;
//                }
//                Object userInfoJsonStr;
//                try{
//                    userInfoJsonStr = stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token);
//                    if (userInfoJsonStr == null) {
//                        throw new ClientException(USER_TOKEN_FAIL);
//                    }
//                }catch (Exception ex){
//                    returnJson((HttpServletResponse) servletResponse,  JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
//                    return;
//                }
//                UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
//                UserContext.setUser(userInfoDTO);
//            }
//
//        }
//        try {
//            filterChain.doFilter(servletRequest, servletResponse);
//        } finally {
//            UserContext.removeUser();
//        }
//    }
//
//
//    private void returnJson(HttpServletResponse response, String json) throws Exception {
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html; charset=utf-8");
//        try (PrintWriter writer = response.getWriter()) {
//            writer.print(json);
//        }
//    }
}